package com.atguigu.dga.governance.assessor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.dga.ds.bean.TDsTaskInstance;
import com.atguigu.dga.ds.service.TDsTaskInstanceService;
import com.atguigu.dga.governance.bean.AssessParam;
import com.atguigu.dga.governance.bean.GovernanceAssessDetail;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import static com.atguigu.dga.common.constants.CommonConst.DS_TASK_STATE_SUCCESS;

@Component("TIME_LINESS")
public class TimeLinessAssessor extends Assessor{

    @Autowired
    TDsTaskInstanceService tDsTaskInstanceService;
    @Override
    public void checkProblem(AssessParam assessParam, GovernanceAssessDetail governanceAssessDetail) throws Exception {
        // 1  求当日产出时效  成功  去当日最后一次成功的时效
        List<TDsTaskInstance> tDsTaskInstanceList = assessParam.getTDsTaskInstanceList();
        if(tDsTaskInstanceList==null) {
            return;
        }
        TDsTaskInstance lastTDsTaskInstance=null;
        for (TDsTaskInstance tDsTaskInstance : tDsTaskInstanceList) {
            if(tDsTaskInstance.getState().toString().equals(DS_TASK_STATE_SUCCESS)){
                if(lastTDsTaskInstance==null
                  ||tDsTaskInstance.getEndTime().getTime()>lastTDsTaskInstance.getEndTime().getTime()){
                    lastTDsTaskInstance=tDsTaskInstance;
                }
            }
        }
        long durationTdMs = lastTDsTaskInstance.getEndTime().getTime() - lastTDsTaskInstance.getSubmitTime().getTime();


        // 2  求前days 的产出时效的平均值 成功
        String metricParamsJson = assessParam.getGovernanceMetric().getMetricParamsJson();
        JSONObject paramJsonObj = JSON.parseObject(metricParamsJson);
        Long paramDays = paramJsonObj.getLong("days");

        QueryWrapper<TDsTaskInstance> queryWrapper = new QueryWrapper<>();
        String assessDate = assessParam.getAssessDate();
        Date assessDateDt = DateUtils.parseDate(assessDate, "yyyy-MM-dd");
        Date fromDate = DateUtils.addDays(assessDateDt, -paramDays.intValue());
        String fromDateStr = DateFormatUtils.format(fromDate, "yyyy-MM-dd");
        queryWrapper.gt("date_format(start_time,'%Y-%m-%d')   ",fromDateStr);
        queryWrapper.le("date_format(start_time,'%Y-%m-%d')   ",assessDate);
        queryWrapper.eq("state",DS_TASK_STATE_SUCCESS);
        queryWrapper.eq("name",assessParam.getTableMetaInfo().getSchemaName()+"."+assessParam.getTableMetaInfo().getTableName());

        List<TDsTaskInstance> beforeDaysTaskInstanceList = tDsTaskInstanceService.list(queryWrapper);

        long durationBeforeDaysSumMs = 0;
        for (TDsTaskInstance tDsTaskInstance : beforeDaysTaskInstanceList) {
            durationBeforeDaysSumMs += tDsTaskInstance.getEndTime().getTime() - tDsTaskInstance.getSubmitTime().getTime();
        }
        long durationBeforeDaysAvgMs= durationBeforeDaysSumMs / beforeDaysTaskInstanceList.size();


        // 3  计算实际超过百分比
        long durationOverMs = durationTdMs - durationBeforeDaysAvgMs;
        BigDecimal overPercent = BigDecimal.valueOf(durationOverMs).movePointRight(2).divide(BigDecimal.valueOf(durationBeforeDaysAvgMs) , 1, BigDecimal.ROUND_HALF_UP)  ;



        // 4 超过百分比 和 参数百分比进行比较 如果大于 0分 批语
        BigDecimal paramPercent = paramJsonObj.getBigDecimal("percent");
        if(overPercent.compareTo(paramPercent)>0){
            governanceAssessDetail.setAssessScore(BigDecimal.ZERO);
            governanceAssessDetail.setAssessProblem("数据产出时间超过平均值");

         }
        governanceAssessDetail.setAssessComment( "当日产出时间："+durationTdMs+"ms"+" 历史产出时间平均值："+durationBeforeDaysAvgMs+"ms" );

    }
}
